package ds.tree;

import java.util.LinkedList;

public class ConnectNodeAtSameLevel {

//	private LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
	private TreeNode Temp = null;
	
	private static class TreeNode{
		int value;
		TreeNode left = null;
		TreeNode right = null;
		TreeNode nextRight = null;
		
		TreeNode(int val){
			this.value = val;
		}
		
		public String toString(){
			return String.valueOf(value);
		}
	}
	private int height(TreeNode node) {
		if(node == null){
			return 0 ; 
		}
		
		return 1+ Math.max(height(node.left), height(node.right));
	}
	
	private void connectNodeOnTheLevel(TreeNode node) {
		int height = height(node);
		for (int i = 2; i <= height; i++) {
			levelOrderTraversal(node, i);
			Temp = null;
		}
		System.out.println();
	}
	private void levelOrderTraversal(TreeNode node, int level)	{
		if(node == null){
			return;
		}
		if(level == 1) {
			if(Temp == null){
				Temp = node;
			}	else	{
				Temp.nextRight = node;
				Temp = node;
			}
			return;
		}
		levelOrderTraversal(node.left,level-1);
		levelOrderTraversal(node.right,level-1);
	}
	
	private static TreeNode tree(){
		
		TreeNode A = new TreeNode(1);
		TreeNode B = new TreeNode(2);
		TreeNode C = new TreeNode(3);
		TreeNode D = new TreeNode(4);
		TreeNode E = new TreeNode(5);
		TreeNode F = new TreeNode(6);
		TreeNode G = new TreeNode(7);
		
		A.left = B;
		A.right = C;
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		
		return A;
	}
	
	
	public static void main(String[] args) {
		ConnectNodeAtSameLevel connectNodeAtSameLvl = new ConnectNodeAtSameLevel();
		connectNodeAtSameLvl.connectNodeOnTheLevel(tree());
		System.out.println("Connected");
	}

}
